<template>
  <div class="material-manage">
    <div class="material-event">
      <div>
        <a-checkbox v-model="filterEmpty" @change="filterEmptyDir">隐藏空目录</a-checkbox>
      </div>
      <div>
        <a-button class="m-r-ssm ant-btn ant-btn-primary" @click="showReplaceMaterialLog">查看文件替换记录</a-button>
        <a-button icon="download" class="m-r-ssm ant-btn ant-btn-primary" @click="downloadPackage">批量下载</a-button>
      </div>
    </div>
    <div>
      <a-table
        bordered
        class="material-table"
        v-if="inRender"
        :expandIcon="expandIcon"
        :columns="columns"
        :rowKey="(record) => record.id"
        :data-source="materialTree"
        :default-expand-all-rows="true"
        :custom-row="customRow"
        :pagination="false"
      >
        <!--    名称    -->
        <template slot="name" slot-scope="text, record">
          <svg v-if="record.refId" class="m-r-sm icon-type" aria-hidden="true">
            <use xlink:href="#icon-wenjianjia"></use>
          </svg>
          <span class="color-text" :title="record.name" style="display: inline-block;width: calc(100% - 110px)">
            <div class="dir-title">
              <div class="dir-title-detail" :style="{color:record.color}" :title="record.nick || record.name">{{ record.nick || record.name }}</div>
              <div class="h-full flex-1"></div>
            </div>
          </span>
        </template>
        <!--    类型    -->
        <template slot="acceptType" slot-scope="text, record">
          <div class="dir-title" v-if="record.directoryDTO && record.directoryDTO.acceptType">
            <div class="dir-title-detail" :title="record.directoryDTO.acceptType">{{ record.directoryDTO.acceptType }}</div>
          </div>
        </template>
        <!--    文件（包含浏览、删除、下载）    -->
        <template slot="files" slot-scope="text, record">
          <div v-if="record.files && record.files.length" class="text-align-left">
            <div
              class="dir-file-item cur-pointer"
              v-for="file in record.files"
              :key="file.id">
              <div>
                <svg width="18" height="18" class="v-t-top m-r-xs">
                  <use :xlink:href="file.icon"></use>
                </svg>
                <span v-if="file.uploadType === 2" class="color-text">（{{ file.unitName }}）</span>
                <span @click="previewNode(file)" class="color-text">{{ file.name }}</span>
                <span class="pull-right hide">
                  <i
                    v-for="auth in file.customHandle.materialFile"
                    :key="Math.random()"
                    :class="[auth.icon]"
                    :title="auth.name"
                    :style="{ color: auth.color }"
                    class="iconfont m-l-sm cursor-pointer"
                    @click.stop="handleClick(auth, file, record)"
                  />
                </span>
              </div>
              <div class="hide w-full m-t-xs f12 file-size">
                <!--     文件大小和上传时间      -->
                {{ file.fileSize }}
                <span class="pull-right">{{ moment(file.uploadTime) }}</span>
              </div>
            </div>
          </div>
        </template>
        <!--    操作    -->
        <template slot="action" slot-scope="text, record">
          <div v-if="record.uplodable && customHandle.materialDirectory && customHandle.materialDirectory.length">
            <span v-for="auth in customHandle.materialDirectory" :key="Math.random()">
              <a-icon
                :type="auth.icon"
                :title="auth.name"
                :style="{ color: auth.color }"
                class="m-r-sm cursor-pointer"
                @click="handleClick(auth, record)">
            </a-icon>
            </span>
          </div>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script>
import materialApi from '@/api/material'
import AButton from 'ant-design-vue/es/button/button'
import projectService from '@/api/projectService'
import moment from 'moment'
import authService from '@/api/authService'
import sqlService from '@/api/sqlService'

const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true,
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '类型',
    dataIndex: 'acceptType',
    key: 'acceptType',
    width: '10%',
    scopedSlots: { customRender: 'acceptType' },
    align: 'center'
  },
  {
    title: '上传内容',
    dataIndex: 'files',
    key: 'files',
    width: '40%',
    align: 'center',
    scopedSlots: { customRender: 'files' }
  },
  {
    title: '操作',
    key: 'action',
    width: '10%',
    scopedSlots: { customRender: 'action' },
    align: 'center'
  }
]

const customHandle = {
  materialDirectory: [
    {
      name: '上传',
      icon: 'upload',
      cb: 'upload'
    }
  ],
  materialFile: [
    {
      name: '浏览',
      icon: 'icon-preview',
      cb: 'preView',
      color: '#8694E7'
    },
    {
      name: '下载',
      icon: 'icon-file-download',
      cb: 'download',
      color: '#7FB646'
    },
    {
      name: '删除',
      icon: 'icon-delete',
      cb: 'remove',
      color: '#E19276'
    }
  ]
}

export default {
  name: 'MaterialUpload',
  props: {
    projectId:{
      type: Number
    }
  },
  data () {
    return {
      columns,
      inRender: false,
      materialTree: [],
      showOpenFolder: false,
      customHandle: {},
      activityName: '',
      projectInfo: {},
      useInfo: '',
      uploadRecord: '',
      fileType: '',
      versionType: 'new',
      filterEmpty: false,
      materialNickName: [ // 杭州用户6个业务需要必传的结果材料
        '建设项目用地预审与选址意见书', '建设项目用地预审与选址意见书附件', '建设项目用地预审与选址意见书附图', // 选址预审
        '建设用地规划许可证', '建设用地规划许可证附件', '建设用地规划许可证附图', // 用地许可
        '建设用地规划许可证', '建设用地规划许可证附件', '建设用地规划许可证附图', // 书证合办
        '建设工程规划许可证', '建设工程规划许可证附件', '建设工程规划许可证附图', // 工程许可
        '乡村建设规划许可证', '乡村建设规划许可证附图', // 乡村许可
        '建设工程规划核实确认书', '建设工程规划核实确认书附件', '建设工程规划核实确认书附图' // 核验合一
      ]
    }
  },
  components: {
    AButton
  },
  created () {
  },
  async mounted () {
    this.getCurrentUser()
    this.getProjectInfo()
    const _this = this
    await _this.materialtable()
    this.Event.$on('_REFRESH_MATERIAL_MANAGER_', (data) => {
      if (data.projectId == _this.projectId) {
        _this.getProjectResourceList()
      }
    })
  },
  methods: {
    materialtable () {
      localStorage.setItem('loginUserName', '禁止上传涉密文件')
    },
    // 获取用户id
    async getCurrentUser () {
      const res = this.userInfo
      this.useInfo = res.id
    },
    async getProjectInfo () {
      const d = await projectService.getProjectInfo(this.projectId)
      this.projectInfo = d.rows[0]
      if (this.projectInfo) {
        this.activityName = this.projectInfo.activityName
      }
      this.getProjectResourceList()
    },
    moment (time) {
      return moment(time).format('YYYY-MM-DD HH:mm:ss')
    },
    // 获取材料数据
    getProjectResourceList () {
      const params = {
        projectId: this.projectId,
        listType: 0 // 0 项目；1 环节；2 业务
      }
      const sqlParam = {
        sqlConfigName: 'getUserRealmName',
        params: {
          userId: this.useInfo
        }
      }
      sqlService.pageQuery(sqlParam).then((res) => {
        let userRealmName = null
        if (res.rows && res.rows[0]) {
          userRealmName = res.rows[0]
        }
        materialApi.getMaterialList(params).then(async (d) => {
          let list = d.map((item) => item.categoryInstDTO)
          this.formatData(list)
          this.treeForEach(list, null, item => {
            if (!item.directoryDTO) {
              item.directoryDTO = {}
            }
            if (item.privilege) {
              let mustPass = item.privilege.indexOf('必传') > -1
              if (this.projectInfo.activityName.indexOf('出证') > -1) {
                mustPass = this.materialValidateByBusiness(item, userRealmName, mustPass)
              }
              if (mustPass) {
                item.color = 'red'
              }
            }
          })
          this.projectResourceList = list
          this.materialTree = this.projectResourceList
          this.initMaterialAuth()
          this.gettitleicon()
        })
      })
    },
    //根据业务类型设置材料必传
    materialValidateByBusiness (data, userRealmName, mustPass) {
      const projectInfo = this.projectInfo
      const bizShortName = projectInfo.F_BUSINESSSHORTNAME

      // 核验合一、复核验收业务，是否通过核验 为 “否”时，结果材料都不必传
      if (['核验合一', '复核验收'].includes(bizShortName)) {
        if (projectInfo.SFTGHY && projectInfo.SFTGHY === '否') {
          return false
        }
      }

      // 其他5个业务，证书信息里，行政许可状态 为“不予许可”时，结果材料都不必传
      if (['选址预审', '书证合办', '用地许可', '工程许可', '乡村许可'].includes(bizShortName)) {
        if (projectInfo.XZXKZT && projectInfo.XZXKZT === '不许可') {
          return false
        }

        // 许可类型为仅选址时 项目选址范围不必传
        if (bizShortName === '选址预审' && projectInfo.YWLX === '2' &&
          data.nick === '项目选址范围') {
          return false
        }
      }

      // 杭州用户
      if (['选址预审', '用地许可', '书证合办', '工程许可', '乡村许可', '核验合一'].includes(bizShortName) && userRealmName &&
        ['杭州市', '桐庐县', '淳安县', '建德市'].includes(userRealmName.REALMNAME) &&
        this.materialNickName.includes(data.nick)) {
        return true
      }

      return mustPass
    },
    treeForEach (list, parent, callback) {
      if (list != null && list.length > 0) {
        list.forEach(item => {
          callback(item, parent)
          this.treeForEach(item.children, item, callback)
        })
      }
    },
    // 对数据进行格式调整
    formatData (list, privilege) {
      list.forEach((item) => {
        if (!item.privilege && privilege) {
          item.privilege = privilege
        }
        if (item.files && item.files.length > 0) {
          item.files = this._.cloneDeep(item.files).map((file) => {
            file.privilege = item.privilege
            file.icon = this.getFileIcon(file.extension)
            return file
          })
        }
        if (item.children) {
          this.formatData(item.children, item.privilege)
        }
      })
    },
    //设置文件的图案
    getFileIcon (extension) {
      switch (extension.toLowerCase()) {
        case '.doc':
        case '.docx':
          return '#icon-file-doc'
        case '.ppt':
        case '.pptx':
          return '#icon-file-ppt'
        case '.xls':
        case '.xlsx':
          return '#icon-file-xls'
        case '.dwg':
          return '#icon-file-dwg'
        case '.txt':
          return '#icon-file-txt'
        case '.pdf':
          return '#icon-file-pdf'
        case '.zip':
          return '#icon-file-zip'
        default :
          return '#icon-file-tree'
      }
    },
    // 下载
    download (file) {
      const params = {
        materialFileId: file.id,
        fileName: file.name,
        mimetype: 'download',
        activityName: this.activityName
      }

      materialApi.downloadMaterial(params)
    },
    // 打包下载
    downPackage (record) {
      const params = {
        projectId: this.projectId,
        categoryInstIds: record.id // 不传，下载整个项目材料
      }
      materialApi.downPackage(params)
    },
    // 预览文件
    preView (file) {
      this.$emit('addTab', { type: 'file', file: file })
    },
    handleSelectUpload (record) {
      this.uploadRecord = record
    },
    //展示提示
    showWarning (message) {
      let dom = null
      const elements = []
      if (this._.isArray(message)) {
        message.forEach((item, index) => {
          elements.push(<div style="text-indent: 30px">{item}</div>)
        })
        dom = <div style="display:flex;flex-direction: column;">{elements}</div>
      } else {
        dom = <div>{message}</div>
      }
      this.$notification.open({
        message: '提示',
        description: dom,
        duration: 0,
        class: 'form-warning',
        icon: <a-icon type="info-circle" theme="twoTone" two-tone-color="red" />
      })
    },
    expandIcon (props) {
      if (props.record.refId) {
        if (props.expanded) {
          props.record.showOpenFolder = true
          return (
            <a-icon
              type="caret-down"
              class="m-r-xs f18"
              style="color:#9C9C9C;"
              onClick={(e) => {
                props.record.showOpenFolder = !props.record.showOpenFolder
                props.onExpand(props.record, e)
              }}
            />
          )
        } else {
          props.record.showOpenFolder = false
          return (
            <a-icon
              type="caret-right"
              class="m-r-xs f18"
              style="color:#9C9C9C;"
              onClick={(e) => {
                props.record.showOpenFolder = !props.record.showOpenFolder
                props.onExpand(props.record, e)
              }}
            />
          )
        }
      } else {
        return (
          <i class="iconfont icon-tree-dir-copy f18 m-r-xs" style="color:#ffb13e"></i>
        )
      }
    },
    // 初始化材料权限
    initMaterialAuth () {
      this.customHandle = customHandle
    },
    // 为每个文件设置操作权限
    gettitleicon () {
      this.materialTree.map((item) => {
        item.children.map((res) => {
          if (res.files && res.files.length > 0) {
            const _this = this
            res.files.map((a) => {
              a.customHandle = customHandle
            })
          }
        })
      })
    },
    handleClick (item, record, directory) {
      switch (item.name) {
        case '上传': {
          this.ReplaceMaterials(record,'upload')
          break
        }
        case '删除': {
          this.ReplaceMaterials(record,'delete')
          break
        }
        case '下载': {
          this.download(record)
          break
        }
        case '浏览': {
          let desc = null
          if (typeof directory.directoryDTO.desc !== 'undefined') {
            desc = JSON.parse(directory.directoryDTO.desc)
          }
          if (desc && desc.isDrafting && desc != null) {
            if (window.config.VUE_APP_WORD_EDIT_TYPE === 'WPS' && navigator.userAgent.includes('Windows')) {
              import('@/api/ntkobackground.min').then(res => {
                this.openNtkoDrafting(record, directory.id, res.ntkoBrowser)
              })
            } else {
              this.fileView(record)
            }
          } else {
            this.fileView(record)
          }
          break
        }
      }
    },
    // 打开ntko在线拟文
    openNtkoDrafting (file, directoryInstId, ntkoBrowser) {
      const ntkoed = ntkoBrowser.ExtensionInstalled()
      if (!ntkoed) {
        this.$message.warn('NTKO插件未安装,请联系管理员')
        return
      }
      authService.getJwtToken().then(jwtToken => {
        const paramMap = {
          id: file.id,
          fileName: file.name,
          directoryInstId: directoryInstId,
          projectId: this.projectId,
          activityName: this.activityName,
          jwtToken: jwtToken,
          type: 'material',
          baseUrl: window.config.VUE_APP_BASE_URL
        }

        let url = `${location.origin}${location.pathname}ntko/ntkoEdit.html`
        Object.keys(paramMap).forEach((key, index) => {
          if (index === 0) {
            url += '?'
          } else {
            url += '&'
          }
          url += key + '=' + encodeURI(paramMap[key])
        })
        ntkoBrowser.openWindow(url, false,
          this.ntkofunction.ProductCaption,
          this.ntkofunction.BrowserProductKey,
          this.ntkofunction.NoExpireKey)
      })
    },
    // 预览文件
    previewNode (item) {
      if (item.type === 'file') {
        this.$emit('addTab', { type: 'file', file: item })
      }
    },
    filterEmptyDir () {
      if (this.filterEmpty) {
        const resultTree = []
        const tree = []
        this.materialTree.forEach(item => {
          if (item.children === '' || item.children === null) {
            // 如果children是空，就去掉
          } else {
            item.children.forEach(item1 => {
              if (item1.files === '' || item1.files === null) {
                // 如果files是空，就去掉
              } else {
                tree.push(item1)
              }
            })
            resultTree.push(item)
          }
        })
        this.materialTree = tree
      } else {
        this.inRender = false
        this.$forceUpdate()
        this.getProjectResourceList()
      }
    },
    //打包下载
    downloadPackage () {
      materialApi.downPackage({ projectId: this.projectId })
    },
    //设置行属性和操作
    customRow (record, index) {
      return {
        on: {
          mouseenter: (event) => {
            const tr = document.querySelector(`.ant-table-tbody tr[data-row-key='${record.id}']`)
            tr.classList.add('hover-row')
          },
          mouseleave: (event) => {
            const tr = document.querySelector(`.ant-table-tbody tr[data-row-key='${record.id}']`)
            setTimeout(() => {
              tr.classList.remove('hover-row')
            }, 100) // 延时0.5秒恢复原背景色
          }
        }
      }
    },
    //替换材料
    ReplaceMaterials(record,type) {
      let owner = this
      owner.$dialog({
        title: '替换结果文件',
        content: () => import('@v/investmentOnline/interfaceMonitor/dialog/ReplaceMaterialsDialog'),
        width: 500,
        scrollable:true,
        bodyStyle: {
          height: type === 'delete'?'350px':'400px',
          overflow: 'hidden',
          padding: '0px'
        },
        centered: true,
        maskClosable: false,
        props: {
          projectId: this.projectId,
          directoryInstId:type === 'delete'?record.materialDirectoryInstId:record.id,
          materialFileId:record.id,
          type:type
        },
        on: {
          ok (ctl) {
            const dialogCtl = ctl.getDialogCtl()
            dialogCtl.replaceMaterials().then(res => {
              if (res.code === 200 || (res.length > 0 && res[0])) {
                owner.$message.success('操作成功')
                owner.Event.$emit('_REFRESH_MATERIAL_MANAGER_', {projectId: owner.projectId})
                ctl.closeDialog()
              } else {
                owner.$message.error('操作失败！')
              }
            })
          },
          cancel() {
          }
        }
      });
    },
    showReplaceMaterialLog() {
      let owner = this
      owner.$dialog({
        title: '材料预览',
        content: () => import('@v/investmentOnline/interfaceMonitor/dialog/ReplaceMaterialsLog'),
        width: 1400,
        scrollable:true,
        bodyStyle: {
          height: '600px',
          overflow: 'hidden',
          padding: '0px'
        },
        centered: true,
        maskClosable: false,
        footer:false,
        props: {
          projectId: this.projectId
        },
        on: {
          ok (ctl) {
          },
          cancel() {
          }
        }
      });
    },
    //预览文件
    fileView(file) {
      debugger
      const ext = ['.docx', '.doc', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf', '.dwg', '.txt', '.jpg', '.jpeg', '.png']
      const extension = file.extension
      const support = ext.includes(extension.toLowerCase())
      if (support) {
        let owner = this
        owner.$dialog({
          content: () => import('@c/FileView/FileView.vue'),
          width: document.documentElement.clientWidth * 0.7,
          scrollable:true,
          bodyStyle: {
            height: document.documentElement.clientHeight * 0.9 + 'px',
            overflow: 'hidden',
            padding: '0px'
          },
          centered: true,
          maskClosable: true,
          footer:false,
          props: {
            params: file
          },
          on: {
            ok (ctl) {
            },
            cancel() {
            }
          }
        });
      } else {
        this.$message.error('目前不支持该格式文件的预览，请下载后本地打开。')
      }
    },
  },
  watch: {
    materialTree (val) {
      this.inRender = true
    }
  }
}
</script>

<style scoped lang="less">
.material-manage {
  background: #fff;
  padding: 10px;
  overflow: auto;
  .material-event{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding:0 2px 9px;
    .select-version-p{
      margin-right: 24px;
      /deep/.ant-radio-button-wrapper{
        border-color: #D9D9D9;
        color: #262626;
        &:focus-within{
          box-shadow: 0 0 0 3px fade(@primary-color, 8%)
        }
      }
      /deep/.ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled) {
        border-color: @primary-color;
        color: @primary-color;
        &::before{
          background-color: @primary-color;
        }
      }
    }
    button{
      margin-left: 10px;
    }
    button:first-of-type{
      margin-left: 0;
    }
  }
  .icon-type{
    width: 18px;
    height: 18px;
    margin-right: 5px;
  }

  /deep/ .ant-table-thead > tr > th {
    text-align: center;
  }

  /deep/ .ant-table-thead > tr > th,
  /deep/ .ant-table-tbody > tr > td {
    padding: 8px 12px;
  }

  .upload-span {
    display: inline-block;
  }
}
.dir-file-item{
  padding: 5px;
  .file-size{
    padding-left: 22px;
    color: #999999;
  }
  &:hover {
    background: rgba(214,217,220,0.20);
    border-radius: 2px;
    .hide{
      display: inline-block;
    }
  }
  & + .dir-file-item{
    padding-top: 10px;
  }
}
.hide{
  display: none;
}
/deep/.ant-table-tbody>tr:hover:not(.ant-table-expanded-row):not(.ant-table-row-selected)>td{
  background: transparent;
}
.color-text{
  color: #666666;
}
.dir-title{
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  overflow: hidden;
  &-detail{
    max-width: 95%;
    overflow: hidden; //超出的文本隐藏
    text-overflow: ellipsis; //溢出用省略号显示
    white-space: nowrap;  // 默认不换行；
  }
  &-required{
    margin-left: 4px;
    color: #f5222d;
    font-size: 16px;
    font-family: SimSun, sans-serif;
    line-height: 1;
  }
}

.text-green{
  color: #6dd400;
}
.text-blue{
  color: #5b99e6;
}

.ant-table-wrapper{
  /deep/ .ant-table{
    .ant-table-row{
      &.hover-row{
        background-color: #e7f1ff;
      }
    }
  }
}
</style>
